package org.example.afree;

import java.util.Arrays;
import java.util.Comparator;

public class Longest_Common_Prefix {
    public static void main(String[] args) {
        String[] strs = {"flower","flow","flight"};
        System.out.println(longestCommonPrefix(strs));
    }
    public static String longestCommonPrefix(String[] strs) {
        strs = Arrays.stream(strs).sorted((s1,s2) -> Integer.compare(s1.length(),s2.length())).toArray(String[]::new);
        String res = "";
        String shortstr = strs[0];
        boolean flag = false;
        for (int i = 0; i < shortstr.length(); i++) {
            for (int j = 1; j < strs.length; j++) {
                if (shortstr.charAt(i) != strs[j].charAt(i)){
                    flag = true;
                    break;
                }
            }
            if (flag) {
                break;
            }else {
                res= res + shortstr.charAt(i);
            }
        }
        return res;
    }
}
